package cn.jiyun.controller;

import cn.jiyun.pojo.User;
import cn.jiyun.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /*页面跳转*/
    @RequestMapping("/{page}")
    public String showPage(@PathVariable String page){
        return page;
    }

    /*添加用户*/
    @RequestMapping("/addUser")
    public String addUser(User user) {
       userService.insertUser(user);
        return "ok";
    }


    /*修改用户*/
    @RequestMapping("/updateUser")
    public String updateUser(User user) {
        userService.updateUser(user);
        return "ok";
    }
    /*回显用户*/
    @RequestMapping("/toUpdate")
    public String toUpdate(Integer id,Model model) {

       User user=userService.toUpdate(id);
       model.addAttribute("user",user);
        return "update";
    }

    /*删除用户*/
    @RequestMapping("/delUser")
    public String delUser(Integer id) {
       userService.delUser(id);
        return "redirect:/user/listUser";
    }


    /*查询所有用户*/
    @RequestMapping("/listUser")
    public String listUser(Model model){
        List<User> list = userService.listUser();
        model.addAttribute("list",list);
        return "list";
    }

    /*用户登录*/
    @RequestMapping("/login")
    public String login(Model model, User user, HttpSession session){
        User uID=userService.login(user);
        if (uID!=null){
            session.setAttribute("uID",uID);
            return "redirect:/user/listUser";
        }
        return "login";
    }


}
